package com.hp.easyBuy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hp.easyBuy.dao.CartDao;
import com.hp.easyBuy.dao.OrderDao;
import com.hp.easyBuy.dao.OrderDetailsDao;
import com.hp.easyBuy.entity.DTO.TCartDto;
import com.hp.easyBuy.entity.TCart;
import com.hp.easyBuy.entity.TOrder;
import com.hp.easyBuy.entity.TOrderDetails;
import com.hp.easyBuy.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, TOrder> implements OrderService {

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private CartDao cartDao;
    @Autowired
    private OrderDetailsDao orderDetailsDao;

    @Override
    //声明式事务处理-保证操作全部成功或者全部失败
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, readOnly = false)
    public boolean account(Long userId, Long addressId) {
        //查询购物车中所有商品的信息
        QueryWrapper<TCartDto> wrapper = new QueryWrapper<>();
        wrapper.eq("c.USERID", userId);
        List<TCartDto> cartDtoList = cartDao.queryAllCart(wrapper);
        //计算获取要结算的购物车中商品的总价
        //循环遍历
        Double totalPrice = 0D;
        for (TCartDto cartDto : cartDtoList) {
            totalPrice += cartDto.getGoodsprice() * cartDto.getNum();
        }
        //封装TOrder订单对象
        TOrder order = new TOrder();
        order.setUserid(userId);
        order.setAddressid(addressId);
        order.setOrdertime(new Date());
        order.setOrderstatus(1L);
        order.setTotalprice(totalPrice);
        //保存订单信息
        orderDao.insert(order);
        System.out.println("orderId = " + order.getOrderid());

        //封装订单详情对象
        //根据购物车的商品来封装，购物车有多少商品就产生多少详情
        for (TCartDto cartDto : cartDtoList) {
            TOrderDetails orderDetails = new TOrderDetails();
            orderDetails.setGoodsid(cartDto.getGoodsid());
            orderDetails.setOrderid(order.getOrderid());    //订单详情关联订单的编号
            orderDetails.setGoodsname(cartDto.getGoodsname());
            orderDetails.setGoodsprice(cartDto.getGoodsprice());
            orderDetails.setGoodsnum(cartDto.getNum());
            orderDetailsDao.insert(orderDetails);
        }

        //清空购物车
        QueryWrapper<TCart> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("USERID",userId);
        cartDao.delete(wrapper1);

        return true;
    }

    //订单列表分页条件查询
    @Override
    public Page<TOrder> page(Integer currentPage, Integer pageSize, Map<String, Object> params) {
        System.out.println(currentPage);
        System.out.println(pageSize);
        System.out.println(params);
        Page<TOrder> page = new Page<TOrder>(currentPage,pageSize);
        QueryWrapper<TOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("o.USERID",params.get("userId"));
        if(null != params && params.size() > 0){
            if(params.get("orderId") != null && !"".equals(params.get("orderId"))){
                queryWrapper.eq("o.ORDERID", params.get("orderId"));
            }
            if(params.get("receiver") != null  && !"".equals(params.get("receiver"))){
                queryWrapper.like("a.receiver", params.get("receiver"));
            }
            if(params.get("status") != null  && !"".equals(params.get("status"))){
                queryWrapper.eq("o.orderstatus", params.get("status"));
            }
        }
        return orderDao.page(page, queryWrapper);
    }

    @Override
    public boolean update(Integer id) {
        return orderDao.update(id);
    }

    @Override
    public TOrder details(Integer id) {
        System.out.println(id);
        TOrder order = orderDao.details(id);
        return order;
    }


     //结算功能
    @Override
    public boolean settle(Long userid,Long addressid) {
        TOrder order = new TOrder();
        order.setAddressid(addressid);
        order.setUserid(userid);
        order.setOrderstatus(1L);
        order.setOrdertime(new Date());
        //获取总价格。根据id获取所有的购物车信息
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("USERID", userid);
        List<TCartDto> cartList = cartDao.getList(queryWrapper);
        if(cartList.size() <= 0){
            return false;
        }
        BigDecimal total = new BigDecimal(0);
        for(TCartDto cart : cartList){
            total = total.add(cart.getGoodsprice().multiply(new BigDecimal(cart.getNum())));
        }
        order.setTotalprice(total);
        //存储该名用户的订单信息到数据库
        orderDao.insert(order);
        //获取订单的序号
        Long newOrderid = order.getOrderid();
        //开始创建订单详情序号
        for(TCartDto cart : cartList){
            TOrderDetails tOrderDetails = new TOrderDetails();
            tOrderDetails.setGoodsid(cart.getGoodsid());
            tOrderDetails.setOrderid(newOrderid);
            tOrderDetails.setGoodsname(cart.getGoodsname());
            tOrderDetails.setGoodsprice(cart.getGoodsprice());
            tOrderDetails.setGoodsnum(cart.getNum());
            //将订单插入数据库
            orderDetailsDao.insert(tOrderDetails);
        }
        //最后删除购物车数据库
        cartDao.delete(queryWrapper);
        return true;
    }
}